import React, { useState, useEffect, useRef } from 'react'
import { APIConfigModal } from './APIConfigModal'

// 模型配置接口
interface ModelConfig {
  id: string
  name: string
  provider: 'openai' | 'groq' | 'openrouter' | 'doubao'
  icon: string
  available: boolean
  needsConfig: boolean
  badge?: string
  description: string
  isFree?: boolean
  isNew?: boolean
  isFast?: boolean
}

// 状态类型
type ConnectionStatus = 'connected' | 'disconnected' | 'testing'

// 组件状态接口
interface ModelConfigState {
  currentModel: string
  isOpen: boolean
  apiConfigured: boolean
  connectionStatus: ConnectionStatus
  availableModels: ModelConfig[]
  showConfigModal: boolean
}

export const ModelConfigWidget: React.FC = () => {
  const [state, setState] = useState<ModelConfigState>({
    currentModel: 'doubao-seed-1-6-250615',
    isOpen: false,
    apiConfigured: true,
    connectionStatus: 'connected',
    availableModels: [],
    showConfigModal: false
  })

  const dropdownRef = useRef<HTMLDivElement>(null)

  // 初始化组件状态
  useEffect(() => {
    // 从localStorage加载配置状态
    const savedConfig = localStorage.getItem('model_config')
    const preferredModel = localStorage.getItem('preferred_model')
    
    if (savedConfig) {
      try {
        const config = JSON.parse(savedConfig)
        setState(prev => ({
          ...prev,
          apiConfigured: config.configuredProviders?.length > 0,
          connectionStatus: config.configuredProviders?.length > 0 ? 'connected' : 'disconnected',
          currentModel: preferredModel || prev.currentModel
        }))
      } catch (error) {
        console.error('Failed to load config from localStorage:', error)
      }
    }
  }, [])

  // 初始化可用模型
  useEffect(() => {
    const models: ModelConfig[] = [
      {
        id: 'doubao-seed-1-6-250615',
        name: '豆包 Seed-1.6',
        provider: 'doubao',
        icon: '🫘',
        available: true,
        needsConfig: false,
        badge: '推荐',
        description: '字节跳动豆包模型，中文优化，多模态支持',
        isFree: true
      },
      {
        id: 'groq-llama-3.1-8b',
        name: 'Llama 3.1 8B',
        provider: 'groq',
        icon: '🚀',
        available: state.apiConfigured,
        needsConfig: !state.apiConfigured,
        badge: '极速',
        description: 'Meta开源模型，响应极快',
        isFree: true,
        isFast: true
      },
      {
        id: 'groq-llama-3.1-70b',
        name: 'Llama 3.1 70B',
        provider: 'groq',
        icon: '🔥',
        available: state.apiConfigured,
        needsConfig: !state.apiConfigured,
        badge: '强大',
        description: '大参数量模型，能力更强',
        isFree: true
      },
      {
        id: 'openai-gpt-3.5-turbo',
        name: 'GPT-3.5 Turbo',
        provider: 'openai',
        icon: '💬',
        available: false,
        needsConfig: true,
        badge: '经典',
        description: 'OpenAI经典模型'
      },
      {
        id: 'openai-gpt-4',
        name: 'GPT-4',
        provider: 'openai',
        icon: '🧠',
        available: false,
        needsConfig: true,
        badge: '顶级',
        description: 'OpenAI最先进模型'
      }
    ]
    setState(prev => ({ ...prev, availableModels: models }))
  }, [state.apiConfigured])

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setState(prev => ({ ...prev, isOpen: false }))
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  // 获取当前模型信息
  const currentModelInfo = state.availableModels.find(m => m.id === state.currentModel) || state.availableModels[0]

  // 状态指示器组件
  const StatusDot: React.FC<{ status: ConnectionStatus }> = ({ status }) => {
    const statusClass = {
      connected: 'bg-green-500',
      disconnected: 'bg-amber-500',
      testing: 'bg-blue-500 status-pulse'
    }

    return (
      <div 
        className={`w-2 h-2 rounded-full ${statusClass[status]}`}
        title={
          status === 'connected' ? '已连接' : 
          status === 'disconnected' ? '未连接' : 
          '测试中'
        }
      />
    )
  }

  // 模型选择处理
  const selectModel = (modelId: string) => {
    const model = state.availableModels.find(m => m.id === modelId)
    if (!model || !model.available) return

    setState(prev => ({ 
      ...prev, 
      currentModel: modelId,
      isOpen: false
    }))
    
    // 保存用户偏好
    localStorage.setItem('preferred_model', modelId)
  }

  // 打开配置弹窗
  const openConfigModal = () => {
    setState(prev => ({ 
      ...prev, 
      showConfigModal: true,
      isOpen: false
    }))
  }

  // 关闭配置弹窗
  const closeConfigModal = () => {
    setState(prev => ({ ...prev, showConfigModal: false }))
  }

  // 配置成功回调
  const handleConfigSuccess = (provider: string, apiKey: string) => {
    setState(prev => ({ 
      ...prev, 
      apiConfigured: true,
      connectionStatus: 'connected',
      showConfigModal: false
    }))
    
    // 保存配置状态到本地存储
    const config = {
      preferredModel: state.currentModel,
      lastProvider: provider,
      configuredProviders: [provider]
    }
    localStorage.setItem('model_config', JSON.stringify(config))
    
    // 切换到该提供商的第一个可用模型
    const firstAvailableModel = state.availableModels.find(m => 
      m.provider === provider && m.needsConfig
    )
    if (firstAvailableModel) {
      setState(prev => ({ ...prev, currentModel: firstAvailableModel.id }))
      localStorage.setItem('preferred_model', firstAvailableModel.id)
    }
  }

  // 切换下拉菜单
  const toggleDropdown = () => {
    setState(prev => ({ ...prev, isOpen: !prev.isOpen }))
  }

  return (
    <div className="relative" ref={dropdownRef}>
      {/* 紧凑模式按钮 */}
      <button
        onClick={toggleDropdown}
        className="flex items-center gap-3 px-4 py-2 rounded-lg border-2 bg-white transition-all hover:border-blue-300 hover:shadow-sm"
        style={{
          border: '2px solid var(--gray-200)',
          borderRadius: 'var(--radius-lg)',
          fontSize: 'var(--text-sm)'
        }}
      >
        {/* 模型信息 */}
        <div className="flex items-center gap-2">
          <span className="text-base">{currentModelInfo?.icon}</span>
          <span className="font-medium">{currentModelInfo?.name}</span>
          {currentModelInfo?.badge && (
            <span className="px-2 py-0.5 text-xs rounded-full bg-blue-100 text-blue-700">
              {currentModelInfo.badge}
            </span>
          )}
        </div>

        {/* 状态和箭头 */}
        <div className="flex items-center gap-2 ml-2">
          <StatusDot status={state.connectionStatus} />
          <span className="text-gray-400" style={{ fontSize: 'var(--text-xs)' }}>
            {state.isOpen ? '▲' : '▼'}
          </span>
        </div>
      </button>


      {/* 展开面板 */}
      {state.isOpen && (
        <div 
          className="absolute top-full mt-2 left-0 bg-white border border-gray-200 rounded-lg shadow-lg z-50 min-w-80"
          style={{
            borderRadius: 'var(--radius-lg)',
            boxShadow: '0 8px 24px rgba(0, 0, 0, 0.12)'
          }}
        >
          {/* 当前状态 */}
          <div className="p-4 border-b border-gray-100">
            <div className="flex items-center gap-2 text-sm">
              <StatusDot status={state.connectionStatus} />
              {state.apiConfigured ? (
                <span className="text-green-700 font-medium">✅ API已配置</span>
              ) : (
                <span className="text-amber-700 font-medium">⚠️ 使用演示模式</span>
              )}
            </div>
          </div>

          {/* 模型选择 */}
          <div className="p-4">
            <h4 className="font-semibold mb-3" style={{ fontSize: 'var(--text-base)' }}>
              选择模型
            </h4>
            
            <div className="space-y-2">
              {state.availableModels.map(model => (
                <div
                  key={model.id}
                  onClick={() => selectModel(model.id)}
                  className={`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all ${
                    state.currentModel === model.id 
                      ? 'bg-blue-50 border-blue-200 border-2' 
                      : model.available
                        ? 'hover:bg-gray-50 border-2 border-transparent'
                        : 'opacity-50 cursor-not-allowed border-2 border-transparent'
                  }`}
                  style={{ borderRadius: 'var(--radius-md)' }}
                >
                  <span className="text-lg">{model.icon}</span>
                  
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="font-medium" style={{ fontSize: 'var(--text-sm)' }}>
                        {model.name}
                      </span>
                      {model.badge && (
                        <span className={`px-2 py-0.5 text-xs rounded-full font-medium ${
                          model.isFree ? 'bg-green-100 text-green-700' :
                          model.isFast ? 'bg-blue-100 text-blue-700' :
                          model.isNew ? 'bg-purple-100 text-purple-700' :
                          'bg-gray-100 text-gray-700'
                        }`}>
                          {model.badge}
                        </span>
                      )}
                    </div>
                    
                    <p className="text-xs text-gray-600 mt-1">
                      {model.description}
                    </p>
                  </div>

                  {/* 选中状态 */}
                  {state.currentModel === model.id && (
                    <div className="text-blue-600">
                      ✓
                    </div>
                  )}
                  
                  {/* 需要配置提示 */}
                  {model.needsConfig && !model.available && (
                    <span className="text-xs text-amber-600 font-medium">
                      需配置
                    </span>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* 快速配置按钮 */}
          {!state.apiConfigured && (
            <div className="p-4 border-t border-gray-100 bg-gray-50">
              <button
                onClick={openConfigModal}
                className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
                style={{ borderRadius: 'var(--radius-lg)' }}
              >
                <span>⚡</span>
                <span>配置免费API</span>
              </button>
              <p className="text-center text-xs text-gray-600 mt-2">
                推荐使用Groq免费API，无需信用卡
              </p>
            </div>
          )}

          {/* 管理配置 */}
          {state.apiConfigured && (
            <div className="p-4 border-t border-gray-100">
              <button
                className="w-full flex items-center justify-center gap-2 px-4 py-2 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
                style={{ borderRadius: 'var(--radius-lg)' }}
              >
                <span>⚙️</span>
                <span>管理配置</span>
              </button>
            </div>
          )}
        </div>
      )}

      {/* API配置弹窗 */}
      <APIConfigModal
        isOpen={state.showConfigModal}
        onClose={closeConfigModal}
        onSuccess={handleConfigSuccess}
      />
    </div>
  )
}